﻿//-----------------------------------------------------------------------
// <copyright file="CreateGroupAction.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace TileTool.Scene.Action.Group
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using TileTool.Log;
    using TileTool.Scene.Entity;
    using TileTool.Scene.Entity.Group;

    /// <summary>
    /// Action to create a new group for a set of entities.
    /// </summary>
    public class CreateGroupAction : SceneAction
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "CreateGroupAction";

        #endregion

        #region Fields - Private

        /// <summary>
        /// Entities that we are going to group.
        /// </summary>
        private IEntityCollection entities;

        /// <summary>
        /// Dictionary which maps from an entity to its pre-grouping parent.
        /// </summary>
        private IDictionary<IEntity, IEntity> entityOldParentDict;

        /// <summary>
        /// Group entity we created.
        /// </summary>
        private GroupEntity groupEntity;

        /// <summary>
        /// Collection which contains the group entity.
        /// </summary>
        private IEntityCollection groupCollection;

        /// <summary>
        /// Scene selection before group was added.
        /// </summary>
        private IEntityCollection oldSelection;

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor for the action.
        /// </summary>
        /// <param name="scene">Scene we are creating a group in.</param>
        /// <param name="ents">Entities to create a group with.</param>
        public CreateGroupAction(ISceneManager scene, IEntityCollection ents)
            : base(scene)
        {
            if (scene == null)
            {
                throw new ArgumentNullException("scene", "Scene must be non-null.");
            }

            if (ents == null)
            {
                throw new ArgumentNullException("ents", "Entity collection must be non-null..");
            }

            if (ents.Count == 0)
            {
                throw new ArgumentException("Entity collection count must be non-zero.");
            }

            this.Valid = false;

            if (ents.Count == 1)
            {
                IEntity ent = ents[0];
                if (ent as GroupEntity != null)
                {
                    return;
                }
            }

            this.oldSelection = this.Scene.Selection;
            this.entities = this.BuildGroupCollection(ents);
            this.entityOldParentDict = this.BuildEntityOldParentDictionary(this.entities);

            this.CreateGroupEntity();
            this.Valid = this.entities.Count != 0;
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Do the action.
        /// </summary>
        public override void Do()
        {
            if (!this.Valid)
            {
                return;
            }

            LogSystem.LogInfo(LogGroup, "Do() - Adding {0} entities to group.", this.entities.Count);

            foreach (IEntity ent in this.entities)
            {
                ent.Parent = this.groupEntity;
            }

            Scene.AddEntities(this.groupCollection);
            Scene.SetSelection(this.groupCollection);
        }

        /// <summary>
        /// Undo the action.
        /// </summary>
        public override void Undo()
        {
            if (!this.Valid)
            {
                return;
            }

            LogSystem.LogInfo(LogGroup, "Undo()");

            foreach (IEntity ent in this.entities)
            {
                ent.Parent = this.entityOldParentDict[ent];
            }

            Scene.RemoveEntities(this.groupCollection);
            Scene.SetSelection(this.oldSelection);
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Given a source set of entities, build the set of entities that we
        /// will actually group.
        /// 
        /// We will only group top level parent entities since their children
        /// will be part of the group as a result of their parent being in the
        /// group.
        /// </summary>
        /// <param name="src">Entity collection to build the set of objects we
        /// will group from.</param>
        /// <returns>Returns the objects we will group.</returns>
        private IEntityCollection BuildGroupCollection(IEntityCollection src)
        {
            ISet<IEntity> inputSet = new HashSet<IEntity>();

            foreach (IEntity entity in src)
            {
                inputSet.Add(entity);
            }

            IEntityCollection res = new EntityCollection();

            foreach (IEntity entity in src)
            {
                if (inputSet.Contains(entity.Parent))
                {
                    continue;
                }

                res.Add(entity);
            }

            Debug.Assert(res.Count != 0, "This should never happen.");

            return res;
        }

        /// <summary>
        /// Build a dictionary which maps from entity to its old parent for the
        /// passed collection of entities.
        /// </summary>
        /// <param name="ents">Entityes to build the dictionary for.</param>
        /// <returns>Returns a dictionary which maps from an entity to its old parent.</returns>
        private IDictionary<IEntity, IEntity> BuildEntityOldParentDictionary(IEntityCollection ents)
        {
            IDictionary<IEntity, IEntity> res = new Dictionary<IEntity, IEntity>();

            foreach (IEntity entity in ents)
            {
                res.Add(entity, entity.Parent);
            }

            return res;
        }

        /// <summary>
        /// Create the group entity we will be using.
        /// </summary>
        private void CreateGroupEntity()
        {
            EntityCreateData createData = new EntityCreateData();

            this.groupEntity = new GroupEntity(createData);
            this.groupEntity.Open = false;

            this.groupCollection = new EntityCollection();
            this.groupCollection.Add(this.groupEntity);
        }

        #endregion
    }
}
